package com.gary.springcloud.lb.Impl;

import com.gary.springcloud.lb.LoadBlancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author pengrui
 * @date 2021/1/9 - 9:43
 */
@Component
public class MyLB implements LoadBlancer {

    /**
     *  当前点击数
     */
    private AtomicInteger currentClickCount = new AtomicInteger(0);

    private final Integer getCurrentAndIncrement() {
        int current;
        int next;
        do {
            current = currentClickCount.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!currentClickCount.compareAndSet(current, next));
        System.out.println("第"+next+"次访问***");
        return next;
    }

    /**
     *   获取下标
     * @param servers
     * @return
     */
    @Override
    public ServiceInstance getService(List<ServiceInstance> servers) {
        int index = getCurrentAndIncrement() % servers.size();
        return servers.get(index);
    }
}
